import { BrowserWindow, nativeImage, session, shell } from 'electron'
import icon from '../renderer/src/assets/images/logo.png'
import { join } from 'path'
import { is } from '@electron-toolkit/utils'
export const width = 1400
export const height = 800

export function createWindow(): BrowserWindow {
  // 创建浏览器窗口。
  const mainWindow = new BrowserWindow({
    width: width,
    height: height,
    show: false,
    autoHideMenuBar: true,
    frame: true,
    icon: nativeImage.createFromDataURL(icon),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })
  // 监听主窗口关闭事件
  mainWindow.on('closed', () => {})

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })
  // 基于 electron-vite cli 的渲染器的热模块替换。
  // 开发时加载远程 URL，生产时加载本地 HTML 文件。
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
  // 开发时打开 DevTools
  if (process.env.VITE_APP_ENV === 'development') {
    mainWindow.webContents.openDevTools()
  }
  // 配置 CSP
  const baseUrl = import.meta.env.VITE_APP_BASE_API + '/'
  const imgSrc = '* data: blob:'
  const fontSrc = '* '
  session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
    callback({
      responseHeaders: {
        ...details.responseHeaders,
        'Content-Security-Policy': `default-src 'self'; script-src 'self'; font-src 'self' ${fontSrc}; style-src 'self' 'unsafe-inline'; img-src 'self' ${imgSrc};connect-src 'self' ${baseUrl};`
      }
    })
  })

  return mainWindow;
}
